#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    ACCEPT_ERR,
    LISTEN_ERR
};

const static int gbacklog = 8;

class TcpServer
{
public:
    TcpServer(int port)
        : _port(port)
    {
    }

    void Init()
    {
        // socket
        _listensocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensocket < 0)
        {
            perror("socket");
            exit(SOCKET_ERR);
        }
        // bind
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;

        socklen_t len = sizeof(server);
        if (::bind(_listensocket, (struct sockaddr *)&server, len) < 0)
        {
            perror("bind");
            exit(BIND_ERR);
        }

        // listen
        int n = ::listen(_listensocket, gbacklog);
        if (n < 0)
        {
            perror("listen");
            exit(LISTEN_ERR);
        }
    }

    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;

    public:
        ThreadData(int sockfd, TcpServer *self)
            : _sockfd(sockfd), _self(self)
        {
        }
    };

    void Loop()
    {
        // signal(SIGCHLD, SIG_IGN);
        bool _isrunning = true;
        while (_isrunning)
        {

            // accept
            sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_listensocket, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                std::cout << "accept error" << std::endl;
                continue;
            }
            // service

            // version--1
            // Service(sockfd);

            // version--2 多进程版本
            pid_t id = fork();
            if (id == 0)
            {
                // child
                ::close(_listensocket);
                if (fork() > 0)    exit(0);

                Service(sockfd); // 孙子进程执行
                exit(0);
            }
            // ::close(sockfd);
            else
            {
                // father
                ::close(sockfd);
                int n = waitpid(id, nullptr, 0);

                if (n > 0) // 忽略最好
                std::cout << "wait success!" << std::endl;
            }

            // version--3 多线程版本
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, this);
            // pthread_create(&tid, nullptr, Excute, td); // 1.成员函数默认有this指针
        }
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self()); // 为了让主线程不等待
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->Service(td->_sockfd);

        delete td;
        return nullptr;
    }

    void Service(int sockfd)
    {
        while (true)
        {
            // read write
            char buffer[1024];
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo = "[Server say]# ";
                echo += buffer;
                ssize_t wn = ::write(sockfd, echo.c_str(), echo.size());
            }
            else if (n == 0)
            {
                std::cout << "client quit" << std::endl;
                break;
            }
            else
            {
                if (errno == EINTR) continue;
                std::cout << "read error" << std::endl;
                break;
            }
        }
        sleep(10);
        ::close(sockfd);
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensocket;
};